#import logging
import atom
import atom.url
import config
import logging
import os
import gdata.service
import gdata.auth
import gdata.alt.appengine
import gdata.spreadsheet.service
#import settings
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required
from google.appengine.ext.webapp.util import run_wsgi_app
from renderer import Renderer
from user_handler import UserHandler
from user_prefs import UserPrefs

SPREADSHEET_KEY = 'tV7NOVp4-gbUVQglSUegsVQ'
WORKSHEET_INPUTS_ID = 'od6'
WORKSHEET_SETTINGS_ID = 'od7'

port = os.environ['SERVER_PORT']
if port and port != '80':
  HOST_NAME = '%s:%s' % (os.environ['SERVER_NAME'], port)
else:
  HOST_NAME = os.environ['SERVER_NAME']






  

class MainPage(webapp.RequestHandler):
    
    def __init__(self):
      self.template_renderer = Renderer('index.html')
      self.client = gdata.spreadsheet.service.SpreadsheetsService()
      self.user_handler = UserHandler()
      self.user_obj = None
      #self.user_obj = UserHandler()
    
    @login_required
    def get(self):
      self.response.headers['Content-Type'] = 'text/html'
      self.template_renderer.self_uri = self.request.url
      #self.user_obj = UserHandler.handleUser()
      self.user_obj = self.user_handler.user_obj
      
      if self.user_obj.spreadsheet_session_token is not None:
        self.client.SetAuthSubToken(self.user_obj.spreadsheet_session_token)
        #self.listSheets()
      
      self.render()
      
#    def listSheets(self):
#      sheets = []
#      
#      feed = self.client.GetListFeed('tV7NOVp4-gbUVQglSUegsVQ','od6')
#      for i, entry in enumerate(feed.entry):
#        for key in entry.custom:
#          value = entry.custom[key].text
#          sheets.append({'title':value, 'key':key})        
#        
#      self.template_renderer.template_values['worksheets'] = sheets
      
    def render(self):
      self.template_renderer.template_values['token'] = self.user_obj.spreadsheet_session_token
      self.response.out.write(self.template_renderer.render())


#class GDataAuthSubLoginHandler(object):
#  
#  def __init__(self):
#    self.client = gdata.spreadsheet.service.SpreadsheetsService()
#    gdata.alt.appengine.run_on_appengine(self.client)

class LoginHandler(webapp.RequestHandler):
    
  def __init__(self):
    self.template_renderer = Renderer('login.html')
    self.client = gdata.spreadsheet.service.SpreadsheetsService()
    self.user_prefs = None
    gdata.alt.appengine.run_on_appengine(self.client)
  
  @login_required    
  def get(self):
    self.user_prefs = UserHandler.handleUser()
    self.template_renderer.self_uri = self.request.url
    if self.request.get('token'):
      self.upgradeToken()
    else:
      self.handleAuthSubLogin()
      
    self.render()
  
  def handleAuthSubLogin(self):
    next_url = self.request.url
    
    auth_sub_url = self.client.GenerateAuthSubURL(next_url, 
        config.GDATA_SCOPE_SPREADSHEETS, secure=False, session=True, 
        domain=config.GDATA_HOSTED_DOMAIN)
    
    self.template_renderer.template_values['auth_sub_url'] = auth_sub_url
    
  def upgradeToken(self):
    single_use_token = gdata.auth.extract_auth_sub_token_from_url(self.request.url)
    self.client.UpgradeToSessionToken(single_use_token)
    session_token = self.client.GetAuthSubToken()
    
    self.template_renderer.template_values['token'] = session_token
    
    self.user_prefs.spreadsheet_session_token = session_token
    db.put(self.user_prefs)
    
  def render(self):
    self.response.out.write(self.template_renderer.render())


PROCESS_STEP_1_START = 'start'
PROCESS_STEP_2_EXECUTE = 'execute'

class ProcessHandler(webapp.RequestHandler):
  def __init__(self):
    self.template_renderer = Renderer('process.html')
    self.user_handler = UserHandler()
    self.user_obj = None
  
  def setUser(self):
    self.user_obj = self.user_handler.handleUser()

  def get(self, step):
    self.setUser()
    #self.response.out.write('in step %s' % step)
    if step == PROCESS_STEP_1_START:
      return self.ProcessStep1()
    elif step == PROCESS_STEP_2_EXECUTE:
      return self.ProcessStep2()
    else:
      pass
    
  def ProcessStep1(self):
    self.template_renderer.template_values['process_step'] = '1'
    self.template_renderer.template_values['next_step'] = PROCESS_STEP_2_EXECUTE
    self.render()
    
  def ProcessStep2(self):
    self.template_renderer.template_values['process_step'] = '2'
    self.render()
    
  def render(self):
    self.template_renderer.template_values['token'] = self.user_obj.spreadsheet_session_token
    self.response.out.write(self.template_renderer.render())


application = webapp.WSGIApplication([('/', MainPage),
                                      ('/login', LoginHandler),
                                      ('/input', ProcessHandler),
                                      ('/process/(.*)', ProcessHandler)], 
                                     debug=True)


def main():
  run_wsgi_app(application)

  
if __name__ == "__main__":
  main()
